package com.ftg.learn.day16.myself;

import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 资源池
 *
 * @author 布衣
 */
public class SpringIocContainer {
    private Map<String, Object> map = new ConcurrentHashMap<>();

    private String xmlPath;

    public SpringIocContainer(String path) {
        this.xmlPath = path;
    }

    public void read() {
        //池

        //解析xml配置文件，提取得到资源列表
        //java 解析xml dom4j jdom sax
        String path = "";
        Document document = null;
        SAXReader reader = new SAXReader();
        try {
            document = reader.read(new File(this.xmlPath));
            Element root = document.getRootElement();
//            所有一级元素
            List<Element> elements = root.elements();
            for (Element element : elements) {
                String id = element.attribute("id").getValue();
                String classPath = element.attribute("class").getValue();
                // 反射生成资源
                Class<Object> c = (Class<Object>) Class.forName(classPath);
                Object instance = c.newInstance();

                //属性赋值
                List<Element> properties = element.elements("property");
                for (int i = 0; i < properties.size(); i++) {
                    String proName = properties.get(i).attribute("name").getValue();
                    String proValue = properties.get(i).attribute("value").getValue();
                    PropertyDescriptor pro = new PropertyDescriptor(proName, c);
                    pro.getWriteMethod().invoke(instance, proValue);
                }
                //资源存储池里面
                map.put(id, instance);
            }

        } catch (DocumentException | ClassNotFoundException | InstantiationException | IllegalAccessException |
                 IntrospectionException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    public Object getBean(String id){
        return this.map.get(id);
    }

}
